import HttpUtils from 'app-http-utils';
/**
 * 创建http
 * @param opt 
 */
export default function createHttp(opt: {
    baseUrl: string // 基础根url
}) {
    const http = new HttpUtils<{ code: number, msg: string, data: any }>();

    // 设置request请求执行方法
    http.setRequest(({ loading, toast, config }) => {
        return {
            request() {
                return new Promise((res) => {
                    const baseUrl = config.baseUrl || opt.baseUrl;
                    const timeout = config.timeout || 10000;
                    const params = {
                        url: baseUrl + config.url,
                        method: config.method,
                        timeout,
                        dataType: config.dataType,
                        headers: {
                            ...config.headers,
                            'Content-Type': 'application/json'
                        },
                        data: {
                            body: {
                                ...config.data,
                                token: '自定义数据'
                            }
                        }
                    };

                    const loadingID = loading && setTimeout(() => {
                        api.showProgress({
                            title: '请稍后',
                            text: ' ',
                            modal: true
                        });
                    }, 800);

                    api.ajax(params, (ret: any, err) => {
                        const data = ret ? ret : { msg: err.msg || '网络异常' };
                        console.log('ajax=================================s');
                        console.log(JSON.stringify(params));
                        console.log(JSON.stringify(data));
                        console.log('ajax=================================e');
                        if (loadingID) {
                            clearTimeout(loadingID);
                            api.hideProgress();
                        }
                        if (toast && data.code !== 200) {
                            api.toast({
                                msg: data.msg,
                                global: true
                            });
                        }
                        res(data);
                    });
                });
            }
        }
    });

    return http;

}


